package com.woniuxy.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class ChatUtils {
    private static final String CHAT_PREFIX = "CHAT";
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 创建唯一的会话标识
     */
    public String createChatId(){
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
        return CHAT_PREFIX+uuid;
    }
    /**
     * 会话存储redis操作
     */
    public void saveChatToRedis(String chatId,String session){
        redisTemplate.opsForList().rightPush("ai:chat:"+chatId,session);
        redisTemplate.expire(chatId,30, TimeUnit.DAYS);
    }
    /**
     * 获取对话
     */
    public String getChatToRedis(String chatId){
        List<String> range = redisTemplate.opsForList().range("ai:chat:"+chatId, -10, -1);
        String sessionHistory = String.join("\n",range);
        return sessionHistory;
    }
}
